package com.tentative.competition.schedule.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tentative.competition.common.config.TentativeCompetitionConfig;
import com.tentative.competition.common.constant.Constants;
import com.tentative.competition.common.core.domain.entity.SysUser;
import com.tentative.competition.common.core.result.PageResult;
import com.tentative.competition.common.enums.*;
import com.tentative.competition.common.model.param.ImitateWorksInfoAddParam;
import com.tentative.competition.common.model.param.SubmitWorksApplyParam;
import com.tentative.competition.common.model.resp.WorkMapInfoResp;
import com.tentative.competition.common.model.schedule.param.ScheduleWorkSearchParam;
import com.tentative.competition.common.model.schedule.param.ScheduleWorksParam;
import com.tentative.competition.common.model.schedule.param.WorksGradeListParam;
import com.tentative.competition.common.model.schedule.resp.*;
import com.tentative.competition.common.model.schedule.vo.FileVo;
import com.tentative.competition.common.model.schedule.vo.ScheduleMemberInfoVo;
import com.tentative.competition.common.utils.DataConversionUtils;
import com.tentative.competition.common.utils.DateUtils;
import com.tentative.competition.common.utils.NumberUtils;
import com.tentative.competition.common.utils.SecurityUtils;
import com.tentative.competition.common.utils.bean.BeanUtils;
import com.tentative.competition.common.utils.file.FileCompressUtils;
import com.tentative.competition.common.utils.file.FileUtils;
import com.tentative.competition.common.utils.file.WorkUtils;
import com.tentative.competition.common.utils.ip.IpUtils;
import com.tentative.competition.schedule.domain.*;
import com.tentative.competition.schedule.mapper.ScheduleWorksMapper;
import com.tentative.competition.schedule.service.*;
import com.tentative.competition.system.service.ISysUserService;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 参赛作品信息表 服务实现类
 * </p>
 *
 * @author SmileH
 * @since 2023-06-22
 */
@Service
public class ScheduleWorksServiceImpl extends ServiceImpl<ScheduleWorksMapper, ScheduleWorks> implements IService<ScheduleWorks> , ScheduleWorksService {

    @Lazy
    @Autowired
    private ScheduleExamineService examineService;

    @Lazy
    @Autowired
    private ScheduleFileInfoService fileInfoService;

    @Autowired
    private DataConversionUtils dataConversionUtils;

    @Lazy
    @Autowired
    private ScheduleAdminService scheduleAdminService;

    @Autowired
    private ScheduleAwardService scheduleAwardService;

    @Autowired
    private ScheduleMemberInfoService memberInfoService;

    @Autowired
    private ScheduleAwardService awardService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ScheduleImitateWorksInfoService imitateWorksInfoService;
    @Autowired
    private WorkUtils workUtils;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private NumberUtils numberUtils;

    private static final String COUNT_KEY = "schedule:works:";
    @Override
    public void submitWorks(ScheduleWorksParam param) {
        //验证码校验
        if (StrUtil.isBlank(param.getCode())){
            throw new RuntimeException("邮箱验证码不能为空！");
        }
        SysUser sysUser = userService.selectUserById(param.getUserId());
        if (ObjUtil.isEmpty(sysUser)){
            throw new RuntimeException("当前用户不存在！");
        }
        //作品数量不超过三个

//        if(StrUtil.isNotBlank(param.getWorksImg())){
//            List<String> list = Arrays.asList(param.getWorksImg().split(","));
//            if (list.size()>BigDecimal.ROUND_FLOOR){
//                throw new RuntimeException("最多只能提交三个作品！");
//            }
//        }
        //pc端才做校验，后台提交不做
        if (param.getIsPc()){
            String key = sysUser.getEmail() + "works_code"+sysUser.getUserId();
            //查询当前邮箱验证码在redis是否存在
            if (redisTemplate.hasKey(key)){
                String code = redisTemplate.opsForValue().get(key);
                if (!code.equals(param.getCode())){
                    throw new RuntimeException("邮箱验证码有误，请检查后输入！");
                }
            }else {
                throw new RuntimeException("邮箱验证码错误或已过期！");
            }
        }
        //获取当前大赛作品提交时间
        ScheduleAdmin admin = scheduleAdminService.getById(param.getScheduleId());
        //验证当前作品提交时间是否在大赛开始时间之前
        if (ObjUtil.isNotEmpty(admin.getScheduleStart())){
            int compareTo = DateUtils.compareTo(new Date(), admin.getScheduleStart());
            if (compareTo<BigDecimal.ROUND_UP){
                throw new RuntimeException("当前赛程为到开始时间，不能提交作品！");
            }
        }
        if (!OperateTypeEnum.TEMPORARY_STORAGE.equals(param.getOperateType())){
            List<ScheduleWorks> list = this.lambdaQuery()
                    .eq(ScheduleWorks::getUserId, sysUser.getUserId())
                    .eq(ObjUtil.isNotEmpty(param.getScheduleId()), ScheduleWorks::getScheduleId, param.getScheduleId())
                    .ne(ScheduleWorks::getWorksStatus,WorksStatusEnum.DRAFT)
                    .list();
            if (CollUtil.isNotEmpty(list)){
                if (list.size()>BigDecimal.ROUND_FLOOR){
                    throw new RuntimeException("最多只能提交三个作品！");
                }
            }
        }
        ScheduleWorks works = new ScheduleWorks();
        BeanUtils.copyBeanProp(works,param);
        works.setUserId(SecurityUtils.getUserId());
        //作品主图用作品高清图的第一张
        if (StrUtil.isNotBlank(works.getWorksImg())){
            List<String> list = Arrays.asList(works.getWorksImg().split(","));
            works.setWorksImgMain(Long.parseLong(list.get(0)));
        }
        if(param.getScheduleId() == null){
            works.setScheduleId(scheduleAdminService.getNowScheduleAdmin().getId());
        }
        //判断报名截止时间
        ScheduleAdmin scheduleAdmin = scheduleAdminService.getById(works.getScheduleId());
        String num = zh2arbaNum(scheduleAdmin.getScheduleLabel().replace("第","").replace("届",""));
        works.setWorksEncoding(numberUtils.getWorksRuleCode(num));
        if (param.getOperateType() != null && OperateTypeEnum.SUBMIT.equals(param.getOperateType())){
            if (ObjUtil.isEmpty(scheduleAdmin)){
                throw new RuntimeException("无法找到赛程数据！");
            }
            if (DateUtils.compareTo(new Date(),scheduleAdmin.getApplyEndTime())> BigDecimal.ROUND_UP){
                throw new RuntimeException("当前报名时间已超过报名截止时间！");
            }
            works.setWorksStatus(WorksStatusEnum.IN_APPROVAL);
        }
        if (param.getOperateType() == null ||
                (param.getOperateType() != null && OperateTypeEnum.TEMPORARY_STORAGE.equals(param.getOperateType()))){
            works.setWorksStatus(WorksStatusEnum.DRAFT);
        }
        String content = this.getContent(works);
        if(StrUtil.isNotBlank(content)){
            works.setContent(content);
        }
        this.saveOrUpdate(works);
        //提交作品审核数据
        if (OperateTypeEnum.SUBMIT.equals(param.getOperateType())){
            //创建审批信息
            ScheduleExamine examine = new ScheduleExamine();
            examine.setExamineStatus(ExamineEnum.US_APPROVE);
            examine.setSubmitTime(new Date());
            examine.setExamineType(ExamineTypeEnum.WORKS);
            examine.setWorksId(works.getId());
            examineService.save(examine);
        }
    }
    public static String zh2arbaNum(String zhNumStr) {
        String[] numStr = {"一","二","三","四","五","六","七","八","九"};

        for (int i = 1; i <= numStr.length; i++) {
            zhNumStr = zhNumStr.replace(numStr[i - 1],String.valueOf(i));
        }

        return zhNumStr;
    }

    public static void main(String[] args) {
        String ss = "第二阶";
        System.out.println(zh2arbaNum(ss));
    }

    @Override
    public void submitMgWorks(ScheduleWorksParam param) {
//        SysUser sysUser = userService.selectUserById(param.getUserId());
//        if (ObjUtil.isEmpty(sysUser)){
//            throw new RuntimeException("当前用户不存在！");
//        }
        //获取当前大赛作品提交时间
        ScheduleWorks works = new ScheduleWorks();
        BeanUtils.copyBeanProp(works,param);
        works.setUserId(SecurityUtils.getUserId());
        if(param.getScheduleId() == null){
            works.setScheduleId(scheduleAdminService.getNowScheduleAdmin().getId());
        }
        ScheduleAdmin scheduleAdmin = scheduleAdminService.getById(works.getScheduleId());
        String num = zh2arbaNum(scheduleAdmin.getScheduleLabel().replace("第","").replace("届",""));
        works.setWorksEncoding(numberUtils.getWorksRuleCode(zh2arbaNum(num)));
        works.setWorksStatus(WorksStatusEnum.APPROVAL_PASS);
        String content = this.getContent(works);
        if(StrUtil.isNotBlank(content)){
            works.setContent(content);
        }
        this.saveOrUpdate(works);
    }

    @Override
    public void updateHomeShowById(Long id) {
        ScheduleWorks works = this.getById(id);
        this.lambdaUpdate().eq(ScheduleWorks::getId,id).set(ScheduleWorks::getHomeShow,!Optional.ofNullable(works.getHomeShow()).orElse(false)).update();
    }

    @Override
    public void updateBackShowById(Long id) {
        ScheduleWorks works = this.getById(id);
        this.lambdaUpdate().eq(ScheduleWorks::getId,id).set(ScheduleWorks::getBackShow,!Optional.ofNullable(works.getBackShow()).orElse(false)).update();
    }

    private String getContent(ScheduleWorks works){
        String content = "";
        List<ScheduleMemberInfo> scheduleMemberInfos = memberInfoService.lambdaQuery()
                .eq(ScheduleMemberInfo::getDelFlag,0)
                .eq(ScheduleMemberInfo::getScheduleId,works.getScheduleId())
                .eq(ScheduleMemberInfo::getUserId,works.getUserId()).list();
        if(CollUtil.isNotEmpty(scheduleMemberInfos)) {
            String formatContent = "%s<br>%s<br>【作品简介】%s<br>【创意理念】%s<br>【研究内容】%s<br>";
            List<String> teamMemberInfos = scheduleMemberInfos.stream()
                    .filter(t -> t.getMemberType().equals(MemberEnum.TEAM_LEADER) || t.getMemberType().equals(MemberEnum.TEAM_MEMBER))
                    .map(ScheduleMemberInfo::getMemberName).collect(Collectors.toList());
            List<String> teacherMemberInfos = scheduleMemberInfos.stream()
                    .filter(t -> t.getMemberType().equals(MemberEnum.TEACHER) || t.getMemberType().equals(MemberEnum.ART_TEACHER))
                    .map(ScheduleMemberInfo::getMemberName).collect(Collectors.toList());
            String teamContent = CollUtil.isNotEmpty(teamMemberInfos) ? ("【团队成员】" + teamMemberInfos.stream().collect(Collectors.joining("、"))) : "";
            String teacherContent = CollUtil.isNotEmpty(teamMemberInfos) ? ("【指导老师】" + teacherMemberInfos.stream().collect(Collectors.joining("、"))) : "";
            String school = CollUtil.isNotEmpty(teamMemberInfos) ? ("【团队成员】" + scheduleMemberInfos.stream()
                    .filter(t -> t.getMemberType().equals(MemberEnum.TEAM_LEADER) || t.getMemberType().equals(MemberEnum.TEAM_MEMBER))
                    .collect(Collectors.toList()).get(0).getUnit()) : "";
            //如果没有团队信息，则自动拼接信息
            content = String.format(formatContent, teamContent, teacherContent, works.getWorksIntro(), works.getWorksOriginality(), works.getStudyContent());
        }
        return content;
    }

    /**
     * 查询我的作品数据
     * @return
     */
    @Override
    public PageResult<ScheduleWorksInfoResp> selectWorksList(ScheduleWorkSearchParam param) {
        IPage<ScheduleWorks> worksIPage = baseMapper.pageList(param, new Page<>(param.getPageNumber(), param.getPageSize()));
        PageResult<ScheduleWorksInfoResp> pageResult = new PageResult<>();
        if(CollUtil.isEmpty(worksIPage.getRecords())){
            return pageResult;
        }
        List<ScheduleWorksInfoResp> resps = com.tentative.competition.common.utils.BeanUtils.copyList(worksIPage.getRecords(),ScheduleWorksInfoResp.class);
        Set<Long> fileIds = CollUtil.newHashSet();
        Set<Long> awardIds = CollUtil.newHashSet();
        for (ScheduleWorksInfoResp resp : resps) {
            if(resp.getWorksImgMain() != null){
                fileIds.add(resp.getWorksImgMain());
            }
            if(resp.getPromise() != null){
                fileIds.add(resp.getPromise());
            }
            if(resp.getWorksVideo() != null){
                List<String> list = Arrays.asList(resp.getWorksVideo().split(","));
                list.stream().filter(x->StrUtil.isNotBlank(x)).forEach(x->fileIds.add(Long.parseLong(x)));
            }
            if(resp.getAwardConfigId() != null){
                awardIds.add(resp.getAwardConfigId());
            }
        }
        //开始组装附件信息
        Map<Long, FileVo> fileVoMap = fileInfoService.selectFileMapByIds(fileIds);
        List<ScheduleAward> awards = scheduleAwardService.lambdaQuery()
                .in(CollUtil.isNotEmpty(awardIds),ScheduleAward::getId,awardIds).list();
        Map<Long,String> awardNameMap = CollUtil.isNotEmpty(awards) ?
                awards.stream().collect(Collectors.toMap(ScheduleAward::getId,ScheduleAward::getAwardName)) :
                new HashMap<>();
        for (ScheduleWorksInfoResp resp : resps) {
            resp.setWorksImgMainUrl(fileVoMap.containsKey(resp.getWorksImgMain()) ? fileVoMap.get(resp.getWorksImgMain()).getFileUrl() : "");
            resp.setPromiseUrl(fileVoMap.containsKey(resp.getPromise()) ? fileVoMap.get(resp.getPromise()).getFileUrl() : "");
            List<FileVo> videoUrlList = CollUtil.newArrayList();
            if (StrUtil.isNotBlank(resp.getWorksVideo())){
                List<String> list = Arrays.asList(resp.getWorksVideo().split(","));
                list.forEach(x->{
                    if (fileVoMap.containsKey(Long.parseLong(x))){
                        videoUrlList.add(fileVoMap.get(Long.parseLong(x)));
                    }
                });
            }
            resp.setWorksVideoList(videoUrlList);
            resp.setAwardConfigName(awardNameMap.containsKey(resp.getAwardConfigId()) ? awardNameMap.get(resp.getAwardConfigId()) : "");
        }
        Iterator<ScheduleWorksInfoResp> iterator = resps.iterator();
        if (iterator.hasNext()){

        }
        //设置上一条及下一条数据
        int count = resps.size();
        for (int i = 0; i < resps.size(); i++) {
            ScheduleWorksInfoResp currentWorksInfoResp = resps.get(i);
            //首条作品不存在上一条数据
            if (i==BigDecimal.ROUND_UP){
                //表示存在下一个-设置下一个数据
                if (count>i+1){
                    ScheduleWorksInfoResp nextWorksInfo = resps.get(i + 1);
                    currentWorksInfoResp.setNextWorksId(nextWorksInfo.getId());
                    currentWorksInfoResp.setNextWorksName(nextWorksInfo.getWorksName());
                }
            }else if (i>BigDecimal.ROUND_UP){
                //设置上一条数据
                ScheduleWorksInfoResp previouWorksInfo = resps.get(i - 1);
                currentWorksInfoResp.setPreviousWorksId(previouWorksInfo.getId());
                currentWorksInfoResp.setPreviousWorksName(previouWorksInfo.getWorksName());
                //判断是否存在下一条
                if (count>i+1){
                    ScheduleWorksInfoResp nextWorksInfo = resps.get(i + 1);
                    currentWorksInfoResp.setNextWorksId(nextWorksInfo.getId());
                    currentWorksInfoResp.setNextWorksName(nextWorksInfo.getWorksName());
                }
            }
        }
        pageResult.setContent(resps);
        pageResult.setTotal(worksIPage.getTotal());
        return pageResult;
    }

    @Override
    public ScheduleWorksResp getInfo(Long id) {
        ScheduleWorks scheduleWorks = this.getById(id);
        if (ObjUtil.isEmpty(scheduleWorks)){
            throw new RuntimeException("找不到对象！");
        }
        ScheduleAdmin scheduleAdmin = scheduleAdminService.getById(scheduleWorks.getScheduleId());
        ScheduleWorksResp resp = new ScheduleWorksResp();
        BeanUtils.copyBeanProp(resp,scheduleWorks);
        if(scheduleAdmin != null){
            resp.setScheduleTitle(scheduleAdmin.getScheduleTitle());
        }
        //获取奖项配置
        List<ScheduleAward> scheduleAwards = awardService.lambdaQuery().list();
        if (CollUtil.isNotEmpty(scheduleAwards)){
            Map<Long, ScheduleAward> awardMap = scheduleAwards.stream().collect(Collectors.toMap(ScheduleAward::getId, Function.identity()));
            if (awardMap.containsKey(resp.getAwardConfigId())){
                resp.setAwardName(awardMap.get(resp.getAwardConfigId()).getAwardName());
            }
        }
        //收集所有附件ID
        final Set<Long> fileIds = CollUtil.newHashSet();
        if (ObjUtil.isNotEmpty(scheduleWorks.getWorksImg())){
            List<String> list = dataConversionUtils.strToList(scheduleWorks.getWorksImg());
            list.forEach(x->fileIds.add(Long.valueOf(x)));
        }
        if (ObjUtil.isNotEmpty(scheduleWorks.getWorksImgMain())){
            fileIds.add(scheduleWorks.getWorksImgMain());
        }
        if (ObjUtil.isNotEmpty(scheduleWorks.getPromise())){
            fileIds.add(scheduleWorks.getPromise());
        }
        if (StrUtil.isNotEmpty(scheduleWorks.getWorksVideo())){
            List<String> list = Arrays.asList(scheduleWorks.getWorksVideo().split(","));
            list.forEach(x->fileIds.add(Long.parseLong(x)));
        }
        Map<Long, FileVo> fileInfoMap = fileInfoService.selectFileMapByIds(fileIds);
        if (ObjUtil.isNotEmpty(scheduleWorks.getWorksImg())){
            List<String> list = dataConversionUtils.strToList(scheduleWorks.getWorksImg());
            List<FileVo> fileList = new ArrayList<>();
            list.forEach(x->{
                if (fileInfoMap.containsKey(Long.valueOf(x))){
                    fileList.add(fileInfoMap.get(Long.valueOf(x)));
                }
            });
            resp.setWorksImgList(fileList);
        }
        if (ObjUtil.isNotEmpty(scheduleWorks.getWorksImgMain())){
            resp.setWorksImgMainVo(fileInfoMap.get(scheduleWorks.getWorksImgMain()));
        }
        if (ObjUtil.isNotEmpty(scheduleWorks.getPromise())){
            resp.setPromiseVo(fileInfoMap.get(scheduleWorks.getPromise()));
        }
        if (StrUtil.isNotEmpty(scheduleWorks.getWorksVideo())){
            List<FileVo> fileVoList = CollUtil.newArrayList();
            List<String> list = Arrays.asList(scheduleWorks.getWorksVideo().split(","));
            list.forEach(x->fileVoList.add(fileInfoMap.get(Long.parseLong(x))));
            resp.setWorksVideoVo(fileVoList);
        }
        //获取成员信息
        if (ObjUtil.isNotEmpty(resp.getUserId())){
            List<ScheduleMemberInfo> scheduleMemberInfos = memberInfoService.lambdaQuery()
                    .eq(ScheduleMemberInfo::getUserId, resp.getUserId())
                    .eq(ScheduleMemberInfo::getScheduleId,resp.getScheduleId())
                    .eq(ScheduleMemberInfo::getDelFlag, 0)
                    .list();
            if (CollUtil.isNotEmpty(scheduleMemberInfos)){
                List<ScheduleMemberInfoVo> vos = scheduleMemberInfos.stream().map(x -> {
                    ScheduleMemberInfoVo vo = new ScheduleMemberInfoVo();
                    BeanUtil.copyProperties(x, vo);
                    return vo;
                }).collect(Collectors.toList());
                resp.setMemberInfoList(vos);
            }
        }

        List<ScheduleWorks> rangWorks = this.lambdaQuery()
//                .eq(ScheduleWorks::getAwardConfigId,scheduleWorks.getAwardConfigId())
                .eq(ScheduleWorks::getDelFlag,0)
                .orderByAsc(ScheduleWorks::getAwardConfigId)
                .orderByAsc(ScheduleWorks::getScheduleId)
                .orderByAsc(ScheduleWorks::getCreateTime).list();

        Integer nowIndex = rangWorks.indexOf(scheduleWorks);
        Integer lastIndex = nowIndex - 1;
        Integer nextIndex = nowIndex + 1;
        if(lastIndex >= 0){
            resp.setLastWorkId(rangWorks.get(lastIndex).getId());
            resp.setLastWorkName(rangWorks.get(lastIndex).getWorksName());
        }
        if(nextIndex >= 0 && nextIndex <= rangWorks.size() - 1){
            resp.setNextWorkId(rangWorks.get(nextIndex).getId());
            resp.setNextWorkName(rangWorks.get(nextIndex).getWorksName());
        }

        //获取作品redis点赞数据
        String key = COUNT_KEY+ resp.getId();
        String ipKey = COUNT_KEY+resp.getId()+":"+IpUtils.getIpAddr();
        //设置点赞标识
        resp.setIsGive(redisTemplate.hasKey(ipKey)?true:false);
        Boolean redisKey = redisTemplate.hasKey(key);
        if (redisKey){
            String count = redisTemplate.opsForValue().get(key);
            resp.setUpvoteCount(Integer.parseInt(count));
        }
        return resp;
    }

    @Override
    public List<PreviousWorksResp> getPreviousWorks() {
        ScheduleInfoResp basicsInfo = scheduleAdminService.getBasicsInfo();
        List<PreviousWorksResp> previousWorks = baseMapper.getPreviousWorks(basicsInfo.getScheduleId());
        if (CollUtil.isEmpty(previousWorks)){
            return new ArrayList<>();
        }
        List<PreviousWorksResp> worksResps = previousWorks.stream().filter(x -> ObjUtil.isNotEmpty(x.getImgFileId())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(worksResps)){
            Set<Long> logoFileIds = worksResps.stream().map(PreviousWorksResp::getImgFileId).collect(Collectors.toSet());
            if (CollUtil.isNotEmpty(logoFileIds)){
                Map<Long, FileVo> longFileVoMap = fileInfoService.selectFileMapByIds(logoFileIds);
                previousWorks.forEach(x->{
                    if (ObjUtil.isNotEmpty(x.getImgFileId())){
                        x.setImgUrl(longFileVoMap.get(x.getImgFileId()).getFileUrl());
                    }
                });
            }
        }
        //设置作品高清图实体
        List<String> imgIds = previousWorks.stream().map(x -> x.getWorksImg()).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(imgIds)){
            final Set<Long> fileIds = CollUtil.newHashSet();
            imgIds.forEach(x->{
                List<String> list = dataConversionUtils.strToList(x);
                list.forEach(y->fileIds.add(Long.valueOf(y)));
            });
            Map<Long, FileVo> longFileVoMap = fileInfoService.selectFileMapByIds(fileIds);
            previousWorks.forEach(x->{
                if (StrUtil.isNotBlank(x.getWorksImg())){
                    List<String> list = dataConversionUtils.strToList(x.getWorksImg());
                    List<FileVo> fileList = new ArrayList<>();
                    list.forEach(j->{
                        if (longFileVoMap.containsKey(Long.valueOf(j))){
                            fileList.add(longFileVoMap.get(Long.valueOf(j)));
                        }
                    });
                    x.setWorksImgVo(fileList);
                }
            });
        }
        for (PreviousWorksResp previousWork : previousWorks) {
            if(StrUtil.isNotBlank(previousWork.getWorksIntro())){
                previousWork.setContent(previousWork.getWorksIntro());
            }else if(StrUtil.isNotBlank(previousWork.getContent())){
                String content = previousWork.getContent().contains("【作品简介】") ?
                        previousWork.getContent().substring(previousWork.getContent().indexOf("【作品简介】"),previousWork.getContent().length() - 1)
                        .replace("&nbsp;","").replace("","")
                                .replaceAll("\\&[a-zA-Z]{0,9};", "").replaceAll("<[^>]*>", "") : "";
                previousWork.setContent(content);
            }
            previousWork.setPicCount(imgIds.size());
        }
        //设置上一条及下一条数据
        int count = previousWorks.size();
        for (int i = 0; i < previousWorks.size(); i++) {
            PreviousWorksResp currentWorksInfoResp = previousWorks.get(i);
            //首条作品不存在上一条数据
            if (i==BigDecimal.ROUND_UP){
                //表示存在下一个-设置下一个数据
                if (count>i+1){
                    PreviousWorksResp nextWorksInfo = previousWorks.get(i + 1);
                    currentWorksInfoResp.setNextWorksId(nextWorksInfo.getWorksId());
                    currentWorksInfoResp.setNextWorksName(nextWorksInfo.getWorksName());
                }
            }else if (i>BigDecimal.ROUND_UP){
                //设置上一条数据
                PreviousWorksResp previouWorksInfo = previousWorks.get(i - 1);
                currentWorksInfoResp.setPreviousWorksId(previouWorksInfo.getWorksId());
                currentWorksInfoResp.setPreviousWorksName(previouWorksInfo.getWorksName());
                //判断是否存在下一条
                if (count>i+1){
                    PreviousWorksResp nextWorksInfo = previousWorks.get(i + 1);
                    currentWorksInfoResp.setNextWorksId(nextWorksInfo.getWorksId());
                    currentWorksInfoResp.setNextWorksName(nextWorksInfo.getWorksName());
                }
            }
        }
        return previousWorks;
    }

    @Override
    public List<HomePreviousWorksResp> getScheduleWorks(String worksName, Long scheduleId) {
        List<HomePreviousWorksResp> scheduleWorks = baseMapper.getScheduleWorks(worksName, scheduleId);
        if (CollUtil.isEmpty(scheduleWorks)){
            return CollUtil.newArrayList();
        }
        scheduleWorks.forEach(x->{
            List<String> list = dataConversionUtils.strToList(x.getWorksImg());
            if (CollUtil.isNotEmpty(list)){
                x.setWorksImgCount(list.size());
            }
        });
        //组装附件
        Set<Long> imgIds = scheduleWorks.stream().map(HomePreviousWorksResp::getWorksImgMain).collect(Collectors.toSet());
        Map<Long, FileVo> longFileVoMap = fileInfoService.selectFileMapByIds(imgIds);
        //获取作品的成员信息
        Set<Long> userIds = scheduleWorks.stream().map(HomePreviousWorksResp::getUserId).collect(Collectors.toSet());
        List<ScheduleMemberInfo> memberInfos = memberInfoService.lambdaQuery()
                .in(ScheduleMemberInfo::getUserId, userIds)
                .eq(ScheduleMemberInfo::getDelFlag, 0)
                .list();
        Map<Long, List<ScheduleMemberInfo>> userMemberMap = new HashMap<>();
        if (CollUtil.isNotEmpty(memberInfos)){
            Map<Long, List<ScheduleMemberInfo>> map = memberInfos.stream().collect(Collectors.groupingBy(x -> x.getUserId()));
            userMemberMap.putAll(map);
        }
        scheduleWorks.forEach(x->{
            if (userMemberMap.containsKey(x.getUserId())){
                StringBuilder str = new StringBuilder();
                List<ScheduleMemberInfo> memberInfoList = userMemberMap.get(x.getUserId());
                String author = "";
                String directionTeacher = "";
                if (CollUtil.isNotEmpty(memberInfoList)){
                    ScheduleMemberInfo leader = memberInfoList.stream()
                            .filter(y -> MemberEnum.TEAM_LEADER.equals(y.getMemberType()))
                            .collect(Collectors.toList())
                            .stream()
                            .findFirst()
                            .orElse(null);
                    if (ObjUtil.isNotEmpty(leader)){
                        author = leader.getMemberName();
                    }
                    ScheduleMemberInfo teacher = memberInfoList.stream()
                            .filter(y -> MemberEnum.TEACHER.equals(y.getMemberType()))
                            .collect(Collectors.toList())
                            .stream()
                            .findFirst()
                            .orElse(null);
                    if (ObjUtil.isNotEmpty(teacher)){
                        directionTeacher = teacher.getMemberName();
                    }
                }
                str.append(x.getAwardName()+"作品：");
                str.append("《"+x.getWorksName()+"》");
                str.append("【作者】"+author);
                str.append("【"+MemberEnum.TEACHER.getName()+"】"+directionTeacher);
                str.append("【设计理念】"+x.getWorksOriginality());
                x.setDescription(str.toString());
            }
            if(StrUtil.isNotBlank(x.getContent())){
                String content = x.getContent().contains("【作品简介】") ?
                        x.getContent().substring(x.getContent().indexOf("【作品简介】"),x.getContent().length() - 1)
                                .replace("&nbsp;","").replace("","")
                                .replaceAll("\\&[a-zA-Z]{0,9};", "").replaceAll("<[^>]*>", "") : "";
                x.setContent(content);
            }
            if (longFileVoMap.containsKey(x.getWorksImgMain())){
                x.setWorksImgMainUrl(longFileVoMap.get(x.getWorksImgMain()).getFileUrl());
            }
        });
        //设置上一条及下一条数据
        int count = scheduleWorks.size();
        for (int i = 0; i < scheduleWorks.size(); i++) {
            HomePreviousWorksResp currentWorksInfoResp = scheduleWorks.get(i);
            //首条作品不存在上一条数据
            if (i==BigDecimal.ROUND_UP){
                //表示存在下一个-设置下一个数据
                if (count>i+1){
                    HomePreviousWorksResp nextWorksInfo = scheduleWorks.get(i + 1);
                    currentWorksInfoResp.setNextWorksId(nextWorksInfo.getWorksId());
                    currentWorksInfoResp.setNextWorksName(nextWorksInfo.getWorksName());
                }
            }else if (i>BigDecimal.ROUND_UP){
                //设置上一条数据
                HomePreviousWorksResp previouWorksInfo = scheduleWorks.get(i - 1);
                currentWorksInfoResp.setPreviousWorksId(previouWorksInfo.getWorksId());
                currentWorksInfoResp.setPreviousWorksName(previouWorksInfo.getWorksName());
                //判断是否存在下一条
                if (count>i+1){
                    HomePreviousWorksResp nextWorksInfo = scheduleWorks.get(i + 1);
                    currentWorksInfoResp.setNextWorksId(nextWorksInfo.getWorksId());
                    currentWorksInfoResp.setNextWorksName(nextWorksInfo.getWorksName());
                }
            }
        }
        return scheduleWorks;
    }

    /**
     * 作品评分列表
     * @param param
     * @return
     */
    @Override
    public PageResult<WorksGradeListResp> selectWorksGradeList(WorksGradeListParam param) {
//        //不查询全部的情况下，默认查询进行中的赛程
        IPage<WorksGradeListResp> respIPage = baseMapper.selectWorksGradeList(param, new Page<>(param.getPageNum(), param.getPageSize()));
        //开始组装附件信息
        Set<Long> fileIds = respIPage.getRecords().stream().map(WorksGradeListResp::getWorksImgMain).collect(Collectors.toSet());
        if(CollUtil.isNotEmpty(fileIds)){
            Map<Long, FileVo> fileVoMap = fileInfoService.selectFileMapByIds(fileIds);
            for (WorksGradeListResp resp : respIPage.getRecords()) {
                resp.setWorksImgMainUrl(fileVoMap.containsKey(resp.getWorksImgMain()) ? fileVoMap.get(resp.getWorksImgMain()).getFileUrl() : "");
            }
        }

        PageResult<WorksGradeListResp> pageResult = new PageResult<>();
        pageResult.setContent(respIPage.getRecords());
        pageResult.setTotal(respIPage.getTotal());
        return pageResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean submitApply(SubmitWorksApplyParam param) {
        if (CollUtil.isEmpty(param.getMemberInfoVos())){
            throw new RuntimeException("成员信息不能为空！");
        }
        //成员身份证不能重复
        Set<String> idCardList = param.getMemberInfoVos().stream().map(ScheduleMemberInfoVo::getIdCard).collect(Collectors.toSet());
        if (idCardList.size()!=param.getMemberInfoVos().size()){
            throw new RuntimeException("成员或老师的身份证信息不能重复！");
        }
        //成员信息不能超过3个
        List<ScheduleMemberInfoVo> collect = param.getMemberInfoVos().stream().filter(x -> MemberEnum.TEAM_MEMBER.equals(x.getMemberType())||MemberEnum.TEAM_LEADER.equals(x.getMemberType())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)&&collect.size()>BigDecimal.ROUND_FLOOR){
            throw new RuntimeException("一个团队最多支持一名队长和两名队员！");
        }
        ScheduleInfoResp basicsInfo = scheduleAdminService.getBasicsInfo();
        Long userId = SecurityUtils.getUserId();
        List<ScheduleMemberInfoVo> teamLeader = param.getMemberInfoVos().stream().filter(x -> MemberEnum.TEAM_LEADER.equals(x.getMemberType())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(teamLeader)){
            if (teamLeader.size()>BigDecimal.ROUND_DOWN){
                throw new RuntimeException("一个作品只能存在一个队长信息！");
            }
        }else {
            throw new RuntimeException("一个作品至少需要添加一个队长信息！");
        }
        //验证老师所在团队是否超出三个
        List<ScheduleMemberInfo> memberInfoList = memberInfoService.lambdaQuery()
                .eq(ScheduleMemberInfo::getScheduleId, basicsInfo.getScheduleId())
                .eq(ScheduleMemberInfo::getDelFlag, 0)
                .list();
        if (ObjUtil.isNotEmpty(memberInfoList)){
            //老师校验
            List<ScheduleMemberInfo> teacherList = memberInfoList.stream().filter(x -> MemberEnum.TEACHER.equals(x.getMemberType()) || MemberEnum.ART_TEACHER.equals(x.getMemberType())).collect(Collectors.toList());
            Map<String, List<ScheduleMemberInfo>> listMap = teacherList.stream().filter(x->StrUtil.isNotBlank(x.getIdCard())).collect(Collectors.groupingBy(x -> x.getIdCard()));
            List<ScheduleMemberInfoVo> teacherListVo = param.getMemberInfoVos().stream().filter(x -> MemberEnum.TEACHER.equals(x.getMemberType()) || MemberEnum.ART_TEACHER.equals(x.getMemberType())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(teacherListVo)){
                teacherListVo.forEach(x->{
                    if (listMap.containsKey(x.getIdCard())){
                        List<ScheduleMemberInfo> collect1 = listMap.get(x.getIdCard()).stream().filter(y -> !y.getUserId().equals(userId)).collect(Collectors.toList());
                        //排除当前团队，如果老师还存在3个或者三个以上，则不能进行报名
                        if (collect1.size() >= BigDecimal.ROUND_FLOOR){
                            throw new RuntimeException("同一指导老师至多指导三个参赛团队，请更换！");
                        }
                    }
                });
            }
            //队员校验
            List<ScheduleMemberInfo> teamMember = memberInfoList.stream().filter(x -> MemberEnum.TEAM_MEMBER.equals(x.getMemberType())||MemberEnum.TEAM_LEADER.equals(x.getMemberType())).collect(Collectors.toList());
            //获取团队下的队员信息
            Map<Long, List<ScheduleMemberInfo>> teamMemberMap = teamMember.stream().collect(Collectors.groupingBy(x -> x.getUserId()));
            Map<Long, List<ScheduleMemberInfoVo>> teamMemberVoMap = param.getMemberInfoVos().stream().collect(Collectors.groupingBy(x -> x.getUserId()));
            //数据对比，不同团队，人员相同人数相同，不能进行报名操作
            for (Map.Entry<Long, List<ScheduleMemberInfoVo>> listEntry : teamMemberVoMap.entrySet()) {
                Set<String> voIdCardList = listEntry.getValue().stream().filter(x->StrUtil.isNotBlank(x.getIdCard())).map(ScheduleMemberInfoVo::getIdCard).collect(Collectors.toSet());
                if (CollUtil.isEmpty(voIdCardList)){
                    break;
                }
                for (Map.Entry<Long, List<ScheduleMemberInfo>> entry : teamMemberMap.entrySet()) {
                    if (!entry.getKey().equals(listEntry.getKey())){
                        Set<String> memberIdCardList = entry.getValue().stream().filter(x->StrUtil.isNotBlank(x.getIdCard())).map(ScheduleMemberInfo::getIdCard).collect(Collectors.toSet());
                        if (CollUtil.isEmpty(memberIdCardList)){
                            continue;
                        }else {
                            //取两者之间的交集，如果交集最后的数据与数据库现有的相同，则抛出异常，排除相同团队
                            List<String> reduce2 = voIdCardList.stream().filter(item -> memberIdCardList.contains(item)).collect(Collectors.toList());
                            if (reduce2.size()==memberIdCardList.size()){
                                throw new RuntimeException("已存在相同成员组成的团队，禁止重复报名！");
                            }
                        }
                    }
                }
            }
        }
        //开始保存成员信息
        List<ScheduleMemberInfo> memberInfos = param.getMemberInfoVos().stream().map(x -> {
            ScheduleMemberInfo info = new ScheduleMemberInfo();
            BeanUtil.copyProperties(x,info);
            info.setScheduleId(basicsInfo.getScheduleId());
            info.setUserId(userId);
            return info;
        }).collect(Collectors.toList());
        //拟参赛信息校验
        if (CollUtil.isEmpty(param.getImitateWorksList())){
            throw new RuntimeException("至少包含一条拟参赛信息数据！");
        }
        //查询当前用户是否已经提交过拟参赛信息
        List<ScheduleImitateWorksInfo> imitateWorksInfos = imitateWorksInfoService.lambdaQuery()
                .eq(ScheduleImitateWorksInfo::getUserId, userId)
                .eq(ScheduleImitateWorksInfo::getScheduleId, basicsInfo.getScheduleId())
                .list();
        if (CollUtil.isNotEmpty(imitateWorksInfos)){
            //如果新增的数据与数据库的数据相加大于3，则不允许新增
            List<ImitateWorksInfoAddParam> addData = param.getImitateWorksList().stream().filter(x -> ObjUtil.isEmpty(x.getId())).collect(Collectors.toList());
            if (imitateWorksInfos.size()+addData.size()>BigDecimal.ROUND_FLOOR){
                throw new RuntimeException("拟参赛数据不得超过三条，如果信息填写错误，请进行修改！");
            }
        }
        //添加拟参赛作品数据
        List<ScheduleImitateWorksInfo> imitateWorksInfos1 = param.getImitateWorksList().stream().map(x -> {
            ScheduleImitateWorksInfo info = new ScheduleImitateWorksInfo();
            BeanUtil.copyProperties(x,info);
            info.setScheduleId(basicsInfo.getScheduleId());
            info.setUserId(userId);
            return info;
        }).collect(Collectors.toList());
        //修改用户信息
        if (StrUtil.isNotBlank(param.getSchoolName())){
            SysUser sysUser = userService.selectUserById(userId);
            sysUser.setSchoolName(param.getSchoolName());
            userService.updateUser(sysUser);
        }
        boolean imitateFlag = imitateWorksInfoService.saveOrUpdateBatch(imitateWorksInfos1);
        boolean meberInfoFlag = memberInfoService.saveOrUpdateBatch(memberInfos);
        return meberInfoFlag && imitateFlag;
    }

    @Override
    public List<GeneralMainResp> getWorksKeyVul() {
        Long userId = SecurityUtils.getUserId();
        if (ObjUtil.isEmpty(userId)){
            throw new RuntimeException("请先登录！");
        }
        List<ScheduleWorks> scheduleWorks = this.lambdaQuery()
                .eq(ScheduleWorks::getUserId, userId)
                .eq(ScheduleWorks::getDelFlag, 0)
                .eq(ScheduleWorks::getWorksStatus, WorksStatusEnum.DRAFT)
                .list();
        if (CollUtil.isNotEmpty(scheduleWorks)){
            return scheduleWorks.stream().map(x->{
                GeneralMainResp resp = new GeneralMainResp();
                resp.setKey(x.getId().toString());
                resp.setVal(x.getWorksName());
                return resp;
            }).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public List<ScheduleMemberInfoVo> getMemberInfoByWorksId(Long worksId) {
        List<ScheduleMemberInfo> memberInfos = memberInfoService.lambdaQuery()
                .eq(ScheduleMemberInfo::getWorksId, worksId)
                .eq(ScheduleMemberInfo::getDelFlag, 0)
                .list();
        if (CollUtil.isEmpty(memberInfos)){
            return CollUtil.newArrayList();
        }
        return memberInfos.stream().map(x->{
            ScheduleMemberInfoVo vo = new ScheduleMemberInfoVo();
            BeanUtil.copyProperties(x,vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public void worksPack(Long worksId) {
        ScheduleWorksResp info = getInfo(worksId);
        if (ObjUtil.isEmpty(info)){
            throw new RuntimeException("当前作品没有查询到需要压缩的文件信息");
        }
        //查询成员信息
        List<ScheduleMemberInfo> memberInfos = memberInfoService.lambdaQuery()
                .eq(ScheduleMemberInfo::getUserId, info.getUserId())
                .eq(ScheduleMemberInfo::getScheduleId, info.getScheduleId())
                .eq(ScheduleMemberInfo::getDelFlag, 0)
                .list();
        List<FileVo> worksImgList = info.getWorksImgList();
        WorkMapInfoResp resp = new WorkMapInfoResp();
        resp.setAwardName(StrUtil.isNotBlank(info.getAwardName()) ? info.getAwardName() : "");
        resp.setWorksName(StrUtil.isNotBlank(info.getWorksName())?info.getWorksName():"");
        resp.setWorksImgMainUrl(ObjUtil.isNotEmpty(info.getWorksImgMainVo())?info.getWorksImgMainVo().getFileUrl():"");
        resp.setLabel(StrUtil.isNotBlank(info.getAwardName())?info.getAwardName():"");
        if (CollUtil.isNotEmpty(memberInfos)){
            List<ScheduleMemberInfo> teamLeader1 = memberInfos.stream().filter(x -> MemberEnum.TEAM_LEADER.equals(x.getMemberType())
            || MemberEnum.TEAM_MEMBER.equals(x.getMemberType())).collect(Collectors.toList());
            List<String> name = teamLeader1.stream().map(ScheduleMemberInfo::getMemberName).collect(Collectors.toList());
            resp.setTeamName(String.join(",",name));
            List<ScheduleMemberInfo> teamLeader = memberInfos.stream().filter(x -> MemberEnum.TEACHER.equals(x.getMemberType())).collect(Collectors.toList());
            if (ObjUtil.isNotEmpty(teamLeader)){
                ScheduleMemberInfo memberInfo = teamLeader.get(0);
                resp.setGuidanceName(memberInfo.getMemberName());
                resp.setUnveilUniversity(memberInfo.getUnit());
            }
        }
        resp.setSynopsis(StrUtil.isNotBlank(resp.getSynopsis())? resp.getSynopsis() : "");
        resp.setWorksOriginality(StrUtil.isNotBlank(resp.getWorksOriginality())? resp.getWorksOriginality() : "");
        resp.setStudyContent(StrUtil.isNotBlank(resp.getStudyContent())? resp.getStudyContent() : "");
        resp.setWorksImgMainUrl(TentativeCompetitionConfig.getProfile() + resp.getWorksImgMainUrl().replace(Constants.RESOURCE_PREFIX,""));
        String content = info.getContent().replace("【","\r【").replaceAll("\\&[a-zA-Z]{0,9};", "").replaceAll("<[^>]*>", "\n\t");
        resp.setContent(content);
        FileVo fileVo = workUtils.uploadWork(resp);
        //文档打包
        if (ObjUtil.isNotEmpty(fileVo)){
            worksImgList.add(fileVo);
        }
        //视频文件
        if (CollUtil.isNotEmpty(info.getWorksVideoVo())){
            worksImgList.addAll(info.getWorksVideoVo());
        }
        for (FileVo vo : worksImgList) {
            vo.setFileUrl(TentativeCompetitionConfig.getProfile() + vo.getFileUrl().replace(Constants.RESOURCE_PREFIX,""));
        }
        FileCompressUtils.downTogetherAndZip(worksImgList,info.getWorksName());
        //删除临时生成的work文件
        FileUtils.deleteFile(fileVo.getFileUrl());
    }

    @Override
    public SubmitWorksApplyParam getImitateWorksInfo() {
        ScheduleInfoResp basicsInfo = scheduleAdminService.getBasicsInfo();
        if (ObjUtil.isEmpty(basicsInfo)){
            throw new RuntimeException("当前没有可用的赛程信息！");
        }
        Long userId = SecurityUtils.getUserId();
        SubmitWorksApplyParam param = new SubmitWorksApplyParam();
        //拟参赛信息
        List<ImitateWorksInfoAddParam> imitateWorksList = CollUtil.newArrayList();
        //成员信息
        List<ScheduleMemberInfoVo> memberInfoVos = CollUtil.newArrayList();
        //获取成员信息
        List<ScheduleMemberInfo> scheduleMemberInfos = memberInfoService.lambdaQuery()
                .eq(ScheduleMemberInfo::getUserId, userId)
                .eq(ScheduleMemberInfo::getScheduleId,basicsInfo.getScheduleId())
                .eq(ScheduleMemberInfo::getDelFlag, 0)
                .list();
        if (CollUtil.isNotEmpty(scheduleMemberInfos)){
            List<ScheduleMemberInfoVo> vos = scheduleMemberInfos.stream().map(x -> {
                ScheduleMemberInfoVo vo = new ScheduleMemberInfoVo();
                BeanUtil.copyProperties(x, vo);
                return vo;
            }).collect(Collectors.toList());
            memberInfoVos.addAll(vos);
        }
        //获取拟参赛作品信息
        List<ScheduleImitateWorksInfo> imitateWorksInfos = imitateWorksInfoService.lambdaQuery()
                .eq(ScheduleImitateWorksInfo::getScheduleId, basicsInfo.getScheduleId())
                .eq(ScheduleImitateWorksInfo::getUserId, userId)
                .list();
        if (CollUtil.isNotEmpty(imitateWorksInfos)){
            List<ImitateWorksInfoAddParam> collect = imitateWorksInfos.stream().map(x -> {
                ImitateWorksInfoAddParam param1 = new ImitateWorksInfoAddParam();
                BeanUtil.copyProperties(x, param1);
                return param1;
            }).collect(Collectors.toList());
            imitateWorksList.addAll(collect);
        }
        SysUser sysUser = userService.selectUserById(userId);
        if (ObjUtil.isNotEmpty(sysUser)){
            param.setSchoolName(sysUser.getSchoolName());
        }
        param.setImitateWorksList(imitateWorksList);
        param.setMemberInfoVos(memberInfoVos);
        return param;
    }

    @Override
    public Boolean upvote(Long worksId) {
        //当前点赞人
        String ipAddr = IpUtils.getIpAddr();
        String ipKey = COUNT_KEY+worksId+":"+ipAddr;
        Boolean ipRedisKey = redisTemplate.hasKey(ipKey);
        if (ipRedisKey){
            throw new RuntimeException("您已经对该作品进行过点赞操作，不能再进行点赞！");
        }else {
            redisTemplate.opsForValue().set(ipKey,"1",3, TimeUnit.DAYS);
        }
        String key = COUNT_KEY+worksId;
        Boolean redisKey = redisTemplate.hasKey(key);
        if (redisKey){
            redisTemplate.opsForValue().increment(key,1);
        }else {
            redisTemplate.opsForValue().set(key,"1");
        }
        return true;
    }

    @Override
    public Boolean cancelUpvote(Long worksId) {
        //当前点赞人
        String ipAddr = IpUtils.getIpAddr();
        String ipKey = COUNT_KEY+worksId+":"+ipAddr;
        Boolean ipRedisKey = redisTemplate.hasKey(ipKey);
        if (ipRedisKey){
            redisTemplate.delete(ipKey);
        }else {
            throw new RuntimeException("您未对该作品进行过点赞操作，不能再进行取消点赞！");
        }
        String key = COUNT_KEY+worksId;
        Boolean redisKey = redisTemplate.hasKey(key);
        if (redisKey){
            redisTemplate.opsForValue().decrement(key,1);
        }
        return true;
    }

    @Override
    public void syncWorksUpvoteCount() {
        ScheduleInfoResp basicsInfo = scheduleAdminService.getBasicsInfo();
        if (ObjUtil.isEmpty(basicsInfo)){
            return;
        }
        List<ScheduleWorks> scheduleWorks = this.lambdaQuery()
                .eq(ScheduleWorks::getDelFlag, 0)
                .eq(ScheduleWorks::getWorksStatus, WorksStatusEnum.APPROVAL_PASS)
                .eq(ScheduleWorks::getScheduleId,basicsInfo.getScheduleId())
                .list();
        scheduleWorks.forEach(x->{
            String key = COUNT_KEY+x.getId();
            Integer hasVul =Integer.parseInt((String)redisTemplate.opsForValue().get(key));
            x.setUpvoteCount(hasVul);
        });
        this.updateBatchById(scheduleWorks);

    }

    /**
     * 获取大赛奖项下拉数据
     * @return
     */
    @Override
    public List<GeneralMainResp> awardsPullDown(Long scheduleId) {
        List<ScheduleAward> list = awardService.lambdaQuery()
                .eq(ScheduleAward::getScheduleId,scheduleId)
                .list();
        if (CollUtil.isNotEmpty(list)){
            return list.stream().map(x->{
                GeneralMainResp resp = new GeneralMainResp();
                resp.setKey(x.getId().toString());
                resp.setVal(x.getAwardName());
                return resp;
            }).collect(Collectors.toList());

        }
        return CollUtil.newArrayList();
    }

    @Override
    public List<ScheduleWorks> getWorksByUserId(Long userId) {
        return this.lambdaQuery().eq(ScheduleWorks::getDelFlag,0).eq(ScheduleWorks::getUserId,userId).list();
    }

}
